英文:
Golang how to pass username and password as JSON body to Post API
问题
使用一个POST API请求,我想要接收一个JWT令牌作为响应。
为此,我想要将用户名和密码作为JSON主体输入发送到API。用户名和密码应该从用户那里以JSON负载的形式动态获取。
目前,我正在使用strings.NewReader来硬编码用户名和密码,但这不适合作为一个Web应用程序,因为会有很多用户使用它。
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"strings"
"time"
"github.com/joho/godotenv"
)
var authToken string
type authorization struct {
AuthorizationToken string `json:"authorizationToken"`
ExpiresTimestamp string `json:"expiresTimestamp"`
}
func main() {
enverr := godotenv.Load(".env")
if enverr != nil {
fmt.Println("Error loading .env file")
os.Exit(1)
}
token()
}
func token() {
authorizationUrl := os.Getenv("authorizationUrl")
requestBody := strings.NewReader(`
{
"name" : "testuser",
"pwd" : "testpwd",
"hName" : "hname"
}
`)
response, err := http.Post(authorizationUrl, "application/json", requestBody)
if err != nil {
panic(err)
}
defer response.Body.Close()
content, _ := ioutil.ReadAll(response.Body)
var result authorization
if err := json.Unmarshal(content, &result); err != nil { // Parse []byte to the go struct pointer
fmt.Println("Can not unmarshal JSON")
}
authToken := result.AuthorizationToken
fmt.Println(PrettyPrint(authToken))
}
func PrettyPrint(i interface{}) string {
s, _ := json.MarshalIndent(i, "", "\t")
return string(s)
}
英文:
Using a post API request I want to receive a JWT token for the response.
For that, I want to send the username and password as JSON body input to the API. The username and password should be taken dynamically from the user as a JSON payload.
Currently, I am hardcoding the user name and password using strings.NewReader which is not suitable as this is a web application and many users will be using it.
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"strings"
"time"
"github.com/joho/godotenv"
)
var authToken string
type authorization struct {
AuthorizationToken string `json:"authorizationToken"`
ExpiresTimestamp string `json:"expiresTimestamp"`
}
func main() {
enverr := godotenv.Load(".env")
if enverr != nil {
fmt.Println("Error loading .env file")
os.Exit(1)
}
token()
}
func token() {
authorizationUrl := os.Getenv("authorizationUrl")
requestBody := strings.NewReader(`
{
"name" : "testuser",
"pwd" : "testpwd",
"hName" : "hname"
}
`)
response, err := http.Post(authorizationUrl, "application/json", requestBody)
if err != nil {
panic(err)
}
defer response.Body.Close()
content, _ := ioutil.ReadAll(response.Body)
var result authorization
if err := json.Unmarshal(content, &result); err != nil { // Parse []byte to the go struct pointer
fmt.Println("Can not unmarshal JSON")
}
authToken := result.AuthorizationToken
fmt.Println(PrettyPrint(authToken))
}
func PrettyPrint(i interface{}) string {
s, _ := json.MarshalIndent(i, "", "\t")
return string(s)
}
答案1
得分: 1
你可以使用HTTP请求体(用于POST请求)。
type Credentials struct {
Username string `json:"username"`
Password string `json:"password"`
}
c := Credentials{}
decoder := json.NewDecoder(r.Body)
defer r.Body.Close()
err := decoder.Decode(&c)
if err != nil {
// 处理错误
}
// 使用它
fmt.Println(c.Username, c.Password)
英文:
You can use http requests body (for POST request)
type Credentials struct {
Username string `json:"username"`
Password string `json:"password"`
}
c := Credentials{}
decoder := json.NewDecoder(r.Body)
defer r.Body.Close()
err: = decoder.Decode(&c)
if err!=nil{
// handle it
}
// use it
fmt.Println(c.Username, c.Password)
</details>
# 答案2
**得分**: 0
如果您打算将应用程序作为可执行文件(在Unix世界中称为命令行)分发,您可以选择以下方式之一:
* 将*用户名*和*密码*作为程序参数`os.Args`提供(省略未更改的代码):
var inputTemplate = `
{
"name" : "USER",
"pwd" : "PWD",
"hName" : "hname"
}
`
func token() {
authorizationUrl := os.Getenv("authorizationUrl")
requestBody := strings.Replace(strings.Replace(inputTemplate, "PWD", os.Args[2], -1), "USER", os.Args[1], -1)
response, err := http.Post(authorizationUrl, "application/json", requestBody)
// ...
}
然后,您应该能够运行编译后的程序:`./filename user password`
* 或者更好的选择是,涉及敏感数据时,从*标准输入*中输入*用户名*和*密码*,并回显密码(隐藏字符):
import (
// ...
"syscall"
"golang.org/x/term"
)
var inputTemplate = `
{
"name" : "USER",
"pwd" : "PWD",
"hName" : "hname"
}
`
func token() {
reader := bufio.NewReader(os.Stdin)
fmt.Print("输入用户名:")
username := reader.ReadString('\n') // 处理错误
fmt.Print("输入密码:")
pwdbytes := term.ReadPassword(int(syscall.Stdin))
password := string(pwdbytes)
authorizationUrl := os.Getenv("authorizationUrl")
requestBody := strings.Replace(strings.Replace(inputTemplate, "PWD", password, -1), "USER", username, -1)
response, err := http.Post(authorizationUrl, "application/json", requestBody)
// ...
}
<details>
<summary>英文:</summary>
If you are intending to distribute the application as an executable (aka command line in the Unix world), you can either:
* Provide the *username* and *password* as program arguments, `os.Args` (omitting unchanged code):
var inputTemplate = `
{
"name" : "USER",
"pwd" : "PWD",
"hName" : "hname"
}
`
func token() {
authorizationUrl := os.Getenv("authorizationUrl")
requestBody := strings.Replace(strings.Replace(inputTemplate, "PWD", os.Args[2], -1), "USER", os.Args[1], -1)
response, err := http.Post(authorizationUrl, "application/json", requestBody)
// ...
}
You should then be able to run your program (once compiled): `./filename user password`
* Or as better alternative, having sensitive data involved, have the *username* and *password* input from *standard input* with password being echoed (hiding the characters):
import (
// ...
"syscall"
"golang.org/x/term"
)
var inputTemplate = `
{
"name" : "USER",
"pwd" : "PWD",
"hName" : "hname"
}
`
func token() {
reader := bufio.NewReader(os.Stdin)
fmt.Print("Enter username: ")
username := reader.ReadString('\n') // handle error
fmt.Print("Enter password: ")
pwdbytes := term.ReadPassword(int(syscall.Stdin))
password := string(pwdbytes)
authorizationUrl := os.Getenv("authorizationUrl")
requestBody := strings.Replace(strings.Replace(inputTemplate, "PWD", password, -1), "USER", username, -1)
response, err := http.Post(authorizationUrl, "application/json", requestBody)
// ...
}
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论