Hier ein Beispiel Struct -> JSON an einen GIN Microwebservice.
Client
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
)
type Lala struct {
Name string
Vorname string
}
func main() {
// Create the record
apiurl := "http://localhost:8080/api/v1/create_record"
var record Lala
record.Vorname = "Hans"
record.Name = "Dampf"
m, _ := json.Marshal(record)
apireq, apierr := http.NewRequest("POST", apiurl, bytes.NewBuffer(m))
apireq.Header.Set("Content-Type", "application/json")
apiclient := &http.Client{}
apiresp, apierr := apiclient.Do(apireq)
if apierr != nil {
fmt.Printf("1 %v", apierr)
}
defer apiresp.Body.Close()
if apiresp.StatusCode == http.StatusCreated {
fmt.Println("0 - Record created.")
} else {
fmt.Printf("1 - ERR: %v", apiresp.Body)
}
}
Server
package main
import (
"fmt"
"net/http"
"github.com/gin-gonic/gin"
)
type Lala struct {
Name string
Vorname string
}
func CreateRecord(c *gin.Context) {
var data Lala
if err := c.BindJSON(&data); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"message": "error occured"})
} else {
fmt.Println(data)
c.JSON(http.StatusCreated, gin.H{"data": data})
}
}
func main() {
r := gin.Default()
r.POST("/api/v1/create_record", CreateRecord)
r.Run()
}
