Golang如何将用户名和密码作为JSON主体传递给Post API

huangapple go评论91阅读模式
英文:

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 = `
{
&quot;name&quot; : &quot;USER&quot;,
&quot;pwd&quot; : &quot;PWD&quot;,
&quot;hName&quot; : &quot;hname&quot;
}
`
func token() {
authorizationUrl := os.Getenv(&quot;authorizationUrl&quot;)
requestBody := strings.Replace(strings.Replace(inputTemplate, &quot;PWD&quot;, os.Args[2], -1), &quot;USER&quot;, os.Args[1], -1)
response, err := http.Post(authorizationUrl, &quot;application/json&quot;, 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 (
// ...
&quot;syscall&quot;
&quot;golang.org/x/term&quot;
)
var inputTemplate = `
{
&quot;name&quot; : &quot;USER&quot;,
&quot;pwd&quot; : &quot;PWD&quot;,
&quot;hName&quot; : &quot;hname&quot;
}
`
func token() {
reader := bufio.NewReader(os.Stdin)
fmt.Print(&quot;Enter username: &quot;)
username := reader.ReadString(&#39;\n&#39;) // handle error
fmt.Print(&quot;Enter password: &quot;)
pwdbytes := term.ReadPassword(int(syscall.Stdin))
password := string(pwdbytes)
authorizationUrl := os.Getenv(&quot;authorizationUrl&quot;)
requestBody := strings.Replace(strings.Replace(inputTemplate, &quot;PWD&quot;, password, -1), &quot;USER&quot;, username, -1)
response, err := http.Post(authorizationUrl, &quot;application/json&quot;, requestBody)
// ...
}
</details>

huangapple
  • 本文由 发表于 2022年7月26日 18:04:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/73121441.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定