客户端
package mainimport ( "c02_get_param/common" "fmt" "zdpgo_resty"
) func main ( ) { client := zdpgo_resty. New ( ) resp, err := client. R ( ) . SetHeader ( "Content-Type" , "application/json" ) . SetBody ( `{"username":"testuser", "password":"testpass"}` ) . SetResult ( & common. AuthSuccess{ } ) . Post ( "http://127.0.0.1:3333/" ) if err != nil { fmt. Println ( "err:" , err) return } fmt. Println ( resp. String ( ) ) resp, err = client. R ( ) . SetHeader ( "Content-Type" , "application/json" ) . SetBody ( [ ] byte ( `{"username":"testuser", "password":"testpass"}` ) ) . SetResult ( & common. AuthSuccess{ } ) . Post ( "http://127.0.0.1:3333/" ) if err != nil { fmt. Println ( "err:" , err) return } fmt. Println ( resp. String ( ) ) resp, err = client. R ( ) . SetBody ( common. UserRequest{ Username: "testuser" , Password: "testpass" } ) . SetResult ( & common. AuthSuccess{ } ) . SetError ( & common. AuthSuccess{ } ) . Post ( "http://127.0.0.1:3333/" ) if err != nil { fmt. Println ( "err:" , err) return } fmt. Println ( resp. String ( ) )
}
请求对象
package commontype UserRequest struct { Username string `json:"username"` Password string `json:"password"`
}
响应对象
package commontype AuthSuccess struct { Code int `json:"code"` Status bool `json:"status"` Message string `json:"message"` Data any `json:"data,omitempty"`
}
服务端
package mainimport ( "c02_get_param/common" "encoding/json" "net/http" "zdpgo_chi" "zdpgo_chi/middleware"
) func main ( ) { r := zdpgo_chi. NewRouter ( ) r. Use ( middleware. RequestID) r. Use ( middleware. RealIP) r. Use ( middleware. Logger) r. Use ( middleware. Recoverer) r. Post ( "/" , func ( w http. ResponseWriter, r * http. Request) { name := r. URL. Query ( ) . Get ( "name" ) age := r. URL. Query ( ) . Get ( "age" ) data := map [ string ] any{ "name" : name, "age" : age, } resp := common. AuthSuccess{ Code: 10000 , Status: true , Message: "success" , } data[ "authorization" ] = r. Header. Get ( "Authorization" ) var req common. UserRequestjson. NewDecoder ( r. Body) . Decode ( & req) defer r. Body. Close ( ) data[ "json" ] = reqresp. Data = datajsonData, err := json. Marshal ( resp) if err != nil { w. Write ( [ ] byte ( err. Error ( ) ) ) return } w. Write ( jsonData) } ) http. ListenAndServe ( ":3333" , r)
}