When I use http://localhost:8080/login?id=ddfd#vcv.com&pwd=dccccf in postman or use it in android app I am getting 404. On curl I get
{"name":"Miss Moneypenny","email":"ddfd#vcv.com","password":"dccccf","mobile":27,"address":"dscsdacc"}
I am not able to understand what can I do to achieve json output in postman and on other platforms like Apps in ios as well as android when I use this api and also on the browser window.
My Main.go code
func getSession() *mgo.Session {
s, err := mgo.Dial("mongodb://localhost")
if err != nil {
panic(err)
}
return s
}
func main() {
r := httprouter.New()
uc := controllers.NewUserController(getSession())
r.GET("/login", uc.LoginUser)
http.ListenAndServe(":8080", r)
}
code in controller/user.go
type UserController struct {
session *mgo.Session
}
func NewUserController(s *mgo.Session) *UserController {
return &UserController{s}
}
func (uc UserController) LoginUser(w http.ResponseWriter, request *http.Request, params httprouter.Params) {
dump,err :=httputil.DumpRequest(request, true)
if err != nil {
http.Error(w, fmt.Sprint(err), http.StatusInternalServerError)
return
}
fmt.Println("Request Dump:\n", string(dump))
encodedValue := request.URL.Query().Get("id")
pwd := request.URL.Query().Get("pwd")
emailId, err := url.QueryUnescape(encodedValue)
if err != nil {
log.Fatal(err)
return
}
u := models.User{}
if err := uc.session.DB("go-web-dev-db").C("users").FindId(emailId + pwd).One(&u); err != nil {
w.WriteHeader(404)
return
}
uj, err := json.Marshal(u)
if err != nil {
fmt.Println(err)
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK) // 200
fmt.Fprintf(w, "%s\n", uj)
}
code in model/user.go
type User struct {
Name string `json:"name" bson:"name"`
Email string `json:"email" bson:"_id"`
Password string `json:"password" bson:"password"`
Mobile int `json:"mobile" bson:"mobile"`
Address string `json:"address" bson:"address"`
}
After using dump when I am using i am using curl 'http://localhost:8080/login?id=ddfd#vcv.com&pwd=dccccf' I get :-
Request Dump:
GET /login?id=ddfd#vcv.com&pwd=dccccf HTTP/1.1
Host: localhost:8080
Accept: */*
User-Agent: curl/7.69.1
After using dump when I am using i am using http://localhost:8080/login?id=ddfd#vcv.com&pwd=dccccf in postman I get :-
Request Dump:
GET /login?id=ddfd#vcv.com&pwd=dccccf HTTP/1.1
Host: localhost:8080
Accept: */*
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
Postman-Token: 8e925738-b8db-4656-9f53-813f4cd53a80
User-Agent: PostmanRuntime/7.24.1
Related
I'm starting to work with fasthttp in Golang and I can't figure out how to send key:value format. In default net/http I did it via url.values. I would appreciate it if you could help me with some sample code!
Image from Burp Suite (How it must look like)
var client *fasthttp.Client
var headerContentTypeJson = []byte("application/json")
type loginData struct {
login string
pass string
}
func main() {
readTimeout, _ := time.ParseDuration("500ms")
writeTimeout, _ := time.ParseDuration("500ms")
maxIdleConnDuration, _ := time.ParseDuration("1h")
client = &fasthttp.Client{
ReadTimeout: readTimeout,
WriteTimeout: writeTimeout,
MaxIdleConnDuration: maxIdleConnDuration,
NoDefaultUserAgentHeader: true, //
DisableHeaderNamesNormalizing: true, //
DisablePathNormalizing: true,
Dial: (&fasthttp.TCPDialer{
Concurrency: 4096,
DNSCacheDuration: time.Hour,
}).Dial,
}
reqTimeout := time.Duration(100) * time.Millisecond
reqData := &loginData{
login: "login",
pass: "password",
}
reqDataByte, _ := json.Marshal(reqData)
req := fasthttp.AcquireRequest()
req.SetRequestURI("https://oskelly.ru/api/v2/account/rawauth")
req.Header.SetMethod(fasthttp.MethodPost)
req.Header.SetContentTypeBytes(headerContentTypeJson)
req.SetBodyRaw(reqDataByte)
resp := fasthttp.AcquireResponse()
err := client.DoTimeout(req, resp, reqTimeout)
fasthttp.ReleaseRequest(req)
if err == nil {
statusCode := resp.StatusCode()
respBody := resp.Body()
fmt.Printf("DEEBUG Response: %s\n", respBody)
if statusCode == http.StatusOK {
respData := &loginData{}
err := json.Unmarshal(respBody, respData)
if err == io.EOF || err == nil {
fmt.Printf("DEBUG Parsed data Response %v\n")
} else {
fmt.Printf("ERR invalid HTTP response code: %d\n", statusCode)
}
}
fasthttp.ReleaseResponse(resp)
}}
enter image description here
Tried to figure out how to integrate url.values into fasthttp
For request Body parameters:
req.Header.SetContentType("application/x-www-form-urlencoded; charset=UTF-8")
Form the request body in key=val string and not json. Can do a simple Stringer impl or req.PostArgs().Add(key, val)
req.PostArgs().Add("login", reqData.Login)
req.PostArgs().Add("pass", reqData.Pass)
Output request
POST / HTTP/1.1
Host: ....
Content-Length: 25
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
login=login&pass=password
I am trying to write a simple Unix domain socket based http server in golang. Here is the code:
package main
import (
"fmt"
"log"
"net/http"
"net"
"os"
"encoding/json"
"os/signal"
"syscall"
)
type UnixListener struct {
ServerMux *http.ServeMux
SocketPath string
UID int
GID int
SocketFileMode os.FileMode
}
//////////////////////////////////////////////////////////////////////
// Start the HTTP server with UNIX socket.
//////////////////////////////////////////////////////////////////////
func (l *UnixListener) Start() error {
listener, err := net.Listen("unix", l.SocketPath)
if err != nil {
return err
}
if err := os.Chown(l.SocketPath, l.UID, l.GID); err != nil {
return err
}
if err := os.Chmod(l.SocketPath, l.SocketFileMode); err != nil {
return err
}
go func(){
shutdown(listener)
}()
svr := http.Server{
Handler: l.ServerMux,
}
if err := svr.Serve(listener); err != nil {
return err
} else {
return nil
}
}
//////////////////////////////////////////////////////////////////////
// Shutdown the HTTP server.
//////////////////////////////////////////////////////////////////////
func shutdown(listener net.Listener) {
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)
s := <-c
listener.Close()
log.Fatalf("[FATAL] Caught a signal. sinal=%s", s)
}
func hello(w http.ResponseWriter, r *http.Request) {
log.Println("Received request %s", r.RequestURI)
fmt.Fprintf(w, "Hello World!\n")
w.Header().Set("ContentType", "application/json")
w.WriteHeader(http.StatusOK)
data := map[string]string { "name" : "satish"}
resp, _ := json.Marshal(data)
if _, err := w.Write(resp); err != nil {
fmt.Printf("Error writing response")
}
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/hello", hello)
unixListener := UnixListener{
ServerMux: mux,
SocketPath: "/temp/test.sock",
UID: 501,
GID: 20,
SocketFileMode: 0644,
}
if err := unixListener.Start(); err != nil {
log.Fatalf("[FATAL] HTTP server error: %s", err)
}
}
But when I send the request to this UDS based server like below, the handler does not seem to be invoked, giving 404 not found error. What is the right way to implement UDS based http server and how to send the http request to it?
curl -vvv --unix-socket /temp/test.sock http:/hello
* Trying /Users/sburnwal/Projects/ACI/temp/test.sock:0...
* Connected to hello (/temp/test.sock) port 80 (#0)
> GET / HTTP/1.1
> Host: hello
> User-Agent: curl/7.84.0
> Accept: */*
>
* Mark bundle as not supporting multiuse
< HTTP/1.1 404 Not Found
< Content-Type: text/plain; charset=utf-8
< X-Content-Type-Options: nosniff
< Date: Mon, 14 Nov 2022 02:38:11 GMT
< Content-Length: 19
<
404 page not found
* Connection #0 to host hello left intact
It appears it's interpreting http:/hello in your command line as the host name and using that for the header. And then requesting / as the path
Try replacing http:/hello in your command line with http://hello/hello. I'm not sure if the single slash vs double-slash is significant. It just looks suspicious.
curl -vvv --unix-socket /temp/test.sock http://hello/hello
Or change your Go code to have a response handler for "/" instead of just for "/hello"
mux.HandleFunc("/hello", hello)
mux.HandleFunc("/", hello)
I've no idea why the VerifyIDToken on Go SDK got panicked. I've used VerifyIDToken on the handler of gin as follows:
r.GET("/idToken/:id", func(c *gin.Context) {
// idToken := c.Param("id")
opt := option.WithCredentialsFile("xxx-secret.json")
app, err := firebase.NewApp(context.Background(), nil, opt)
if err != nil {
fmt.Println(fmt.Errorf("error initializing app: %v", err))
}
client, err := app.Auth(context.Background())
if err != nil {
fmt.Println("error getting Auth client: %v\n", err)
fmt.Println(client)
}
idToken := c.Param("id")
fmt.Println("idTaken = ", idToken)
token, err := client.VerifyIDToken(context.Background(), idToken)
if err != nil {
fmt.Println("error verifying ID token: %v\n", err)
}
fmt.Println("Verified ID token: %v\n", token)
})
I've called above API as follows:
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
user.getIdToken(/* forceRefresh */ true).then(function(idToken) {
// Send token to your backend via HTTPS
// ...
axios
.get('https://xx.xxx.com/idToken/' + idToken)
.then(response => {
this.response = response;
console.log(response);
if (response.data.update == "ok") {
this.acceptOKresponse = true;
}
})
}).catch(function(error) {
// Handle error
});
Then, Followings appeared on the server console:
idTaken = eyJhbGciOiJSUzI1NiIsImtpZCI6IjBlYTNmN2EwMjQ4YmU0ZTBkZjAyYWVlZWIyMGIxZDJlMmI3ZjI0NzQiLCJ0eXAiOiJKV1QifQ.eyJuYW1lIjoi5LiK55Sw5YGl5LmLIiwiaXNzIjoiaHR0cHM6Ly9zZWN1cmV0b2tlbi5nb29nbGUuY29tL21hZ2ljbGFiZWwtYjQ0NjkiLCJhdWQiOiJtYWdpY2xhYmVsLWI0NDY5IiwiYXV0aF90aW1lIjoxNTgzMTE2MjQwLCJ1c2VyX2lkIjoiS0V5b3dYZnd4NFNqbEMwakdsTnVzcDU0c0xQMiIsInN1YiI6IktFeW93WGZ3eDRTamxDMGpHbE51c3A1NHNMUDIiLCJpYXQiOjE1ODMxMjM3NTcsImV4cCI6MTU4MzEyNzM1NywiZW1haWwiOiJnZGUwMDEwN0BuaWZ0eS5jb20iLCJlbWFpbF92ZXJpZmllZCI6dHJ1ZSwiZmlyZWJhc2UiOnsiaWRlbnRpdGllcyI6eyJlbWFpbCI6WyJnZGUwMDEwN0BuaWZ0eS5jb20iXX0sInNpZ25faW5fcHJvdmlkZXIiOiJwYXNzd29yZCJ9fQ.ABnMA6iOITghzo_WzgdDwssODiLsswVSlKod6w5CHcnkJOQVKqQIynZufTQvcF8nQO77MYXikZD8TQE_uGq3EpHWQibun67mvN74GnPaguzgvpjQ-PqIOzuhnn2n2SpHSacdREtFkwtj1S66bhigbuTJbqr8jQtIEIB6gfmnObwcmpNRsc-GGR45xjWAO6UY4Ygw4xDcHsHGXwL6SA-HbDuSZGeQfXtdPt94taJfrQQB9nr_7gRjttQLz4ongh-g-fMSpWx3z8lmQgPwgg4GyChYPZ6_hdEV3AWFJTHptE2X8RCV6HfpZB6EGwvLQr6ZrC01uodGTg87BvtPrersjA
2020/03/02 13:35:58 [Recovery] 2020/03/02 - 13:35:58 panic recovered:
GET /idToken/eyJhbGciOiJSUzI1NiIsImtpZCI6IjBlYTNmN2EwMjQ4YmU0ZTBkZjAyYWVlZWIyMGIxZDJlMmI3ZjI0NzQiLCJ0eXAiOiJKV1QifQ.eyJuYW1lIjoi5LiK55Sw5YGl5LmLIiwiaXNzIjoiaHR0cHM6Ly9zZWN1cmV0b2tlbi5nb29nbGUuY29tL21hZ2ljbGFiZWwtYjQ0NjkiLCJhdWQiOiJtYWdpY2xhYmVsLWI0NDY5IiwiYXV0aF90aW1lIjoxNTgzMTE2MjQwLCJ1c2VyX2lkIjoiS0V5b3dYZnd4NFNqbEMwakdsTnVzcDU0c0xQMiIsInN1YiI6IktFeW93WGZ3eDRTamxDMGpHbE51c3A1NHNMUDIiLCJpYXQiOjE1ODMxMjM3NTcsImV4cCI6MTU4MzEyNzM1NywiZW1haWwiOiJnZGUwMDEwN0BuaWZ0eS5jb20iLCJlbWFpbF92ZXJpZmllZCI6dHJ1ZSwiZmlyZWJhc2UiOnsiaWRlbnRpdGllcyI6eyJlbWFpbCI6WyJnZGUwMDEwN0BuaWZ0eS5jb20iXX0sInNpZ25faW5fcHJvdmlkZXIiOiJwYXNzd29yZCJ9fQ.ABnMA6iOITghzo_WzgdDwssODiLsswVSlKod6w5CHcnkJOQVKqQIynZufTQvcF8nQO77MYXikZD8TQE_uGq3EpHWQibun67mvN74GnPaguzgvpjQ-PqIOzuhnn2n2SpHSacdREtFkwtj1S66bhigbuTJbqr8jQtIEIB6gfmnObwcmpNRsc-GGR45xjWAO6UY4Ygw4xDcHsHGXwL6SA-HbDuSZGeQfXtdPt94taJfrQQB9nr_7gRjttQLz4ongh-g-fMSpWx3z8lmQgPwgg4GyChYPZ6_hdEV3AWFJTHptE2X8RCV6HfpZB6EGwvLQr6ZrC01uodGTg87BvtPrersjA HTTP/1.1
Host: ml.uedasoft.com
Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate, br
Accept-Language: ja,en;q=0.9,fr;q=0.8,en-US;q=0.7
Connection: Keep-Alive
Origin: http://localhost:8080
Referer: http://localhost:8080/
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: cross-site
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.122 Safari/537.36
X-Forwarded-For: 125.172.88.148
X-Forwarded-Host: ml.uedasoft.com
X-Forwarded-Server: ml.uedasoft.com
runtime error: invalid memory address or nil pointer dereference
/usr/local/go/src/runtime/panic.go:199 (0x5595f)
panicmem: panic(memoryError)
/usr/local/go/src/runtime/signal_unix.go:394 (0x55838)
sigpanic: panicmem()
/usr/local/go/src/runtime/internal/atomic/atomic_arm.go:103 (0x126db)
goXadd64: *(*int)(nil) = 0 // crash on unaligned uint64
/home/ueda/.go/src/go.opencensus.io/trace/trace.go:483 (0x50b937)
(*defaultIDGenerator).NewSpanID: id = atomic.AddUint64(&gen.nextSpanID, gen.spanIDInc)
/home/ueda/.go/src/go.opencensus.io/trace/trace.go:196 (0x50a26f)
startSpanInternal: span.spanContext.SpanID = cfg.IDGenerator.NewSpanID()
/home/ueda/.go/src/go.opencensus.io/trace/trace.go:162 (0x50a117)
StartSpan: span := startSpanInternal(name, parent != SpanContext{}, parent, false, opts)
/home/ueda/.go/src/go.opencensus.io/plugin/ochttp/trace.go:58 (0x51713b)
(*traceTransport).RoundTrip: ctx, span := trace.StartSpan(req.Context(), name,
/home/ueda/.go/src/go.opencensus.io/plugin/ochttp/client_stats.go:54 (0x516b1b)
statsTransport.RoundTrip: resp, err := t.base.RoundTrip(req)
/home/ueda/.go/src/go.opencensus.io/plugin/ochttp/client.go:89 (0x5165c7)
(*Transport).RoundTrip: return rt.RoundTrip(req)
/usr/local/go/src/net/http/client.go:250 (0x25ec27)
send: resp, err = rt.RoundTrip(req)
/usr/local/go/src/net/http/client.go:174 (0x25e6ef)
(*Client).send: resp, didTimeout, err = send(req, c.transport(), deadline)
/usr/local/go/src/net/http/client.go:641 (0x25fb17)
(*Client).do: if resp, didTimeout, err = c.send(req, deadline); err != nil {
/usr/local/go/src/net/http/client.go:509 (0x4f9def)
(*Client).Do: return c.do(req)
/home/ueda/.go/src/golang.org/x/net/context/ctxhttp/ctxhttp.go:30 (0x4f9d60)
Do: resp, err := client.Do(req.WithContext(ctx))
/home/ueda/.go/src/firebase.google.com/go/auth/token_verifier.go:92 (0x59750b)
(*httpKeySource).refreshKeys: resp, err := ctxhttp.Do(ctx, k.HTTPClient, req)
/home/ueda/.go/src/firebase.google.com/go/auth/token_verifier.go:72 (0x59733b)
(*httpKeySource).Keys: err := k.refreshKeys(ctx)
/home/ueda/.go/src/firebase.google.com/go/auth/token_verifier.go:129 (0x5979e3)
verifyToken: keys, err := ks.Keys(ctx)
/home/ueda/.go/src/firebase.google.com/go/auth/auth.go:223 (0x59529f)
(*Client).VerifyIDToken: if err := verifyToken(ctx, idToken, c.keySource); err != nil {
/home/ueda/ml/main.go:97 (0x5fdc33)
main.func5: token, err := client.VerifyIDToken(context.Background(), idToken)
/home/ueda/.go/src/github.com/gin-gonic/gin/context.go:147 (0x48710f)
(*Context).Next: c.handlers[c.index](c)
/home/ueda/.go/src/github.com/gin-gonic/gin/recovery.go:83 (0x497efb)
RecoveryWithWriter.func1: c.Next()
/home/ueda/.go/src/github.com/gin-gonic/gin/context.go:147 (0x48710f)
(*Context).Next: c.handlers[c.index](c)
/home/ueda/.go/src/github.com/gin-gonic/gin/logger.go:241 (0x497347)
LoggerWithConfig.func1: c.Next()
/home/ueda/.go/src/github.com/gin-gonic/gin/context.go:147 (0x48710f)
(*Context).Next: c.handlers[c.index](c)
/home/ueda/.go/src/github.com/gin-gonic/gin/gin.go:412 (0x48f8bf)
(*Engine).handleHTTPRequest: c.Next()
/home/ueda/.go/src/github.com/gin-gonic/gin/gin.go:370 (0x48f19f)
(*Engine).ServeHTTP: engine.handleHTTPRequest(c)
/usr/local/go/src/net/http/server.go:2802 (0x2a2c7f)
serverHandler.ServeHTTP: handler.ServeHTTP(rw, req)
/usr/local/go/src/net/http/server.go:1890 (0x29f12f)
(*conn).serve: serverHandler{c.server}.ServeHTTP(w, w.req)
/usr/local/go/src/runtime/asm_arm.s:868 (0x6c86f)
goexit: MOVW R0, R0 // NOP
[GIN] 2020/03/02 - 13:35:58 | 500 | 13.345389ms | 125.172.88.148 | GET /idToken/eyJhbGciOiJSUzI1NiIsImtpZCI6IjBlYTNmN2EwMjQ4YmU0ZTBkZjAyYWVlZWIyMGIxZDJlMmI3ZjI0NzQiLCJ0eXAiOiJKV1QifQ.eyJuYW1lIjoi5LiK55Sw5YGl5LmLIiwiaXNzIjoiaHR0cHM6Ly9zZWN1cmV0b2tlbi5nb29nbGUuY29tL21hZ2ljbGFiZWwtYjQ0NjkiLCJhdWQiOiJtYWdpY2xhYmVsLWI0NDY5IiwiYXV0aF90aW1lIjoxNTgzMTE2MjQwLCJ1c2VyX2lkIjoiS0V5b3dYZnd4NFNqbEMwakdsTnVzcDU0c0xQMiIsInN1YiI6IktFeW93WGZ3eDRTamxDMGpHbE51c3A1NHNMUDIiLCJpYXQiOjE1ODMxMjM3NTcsImV4cCI6MTU4MzEyNzM1NywiZW1haWwiOiJnZGUwMDEwN0BuaWZ0eS5jb20iLCJlbWFpbF92ZXJpZmllZCI6dHJ1ZSwiZmlyZWJhc2UiOnsiaWRlbnRpdGllcyI6eyJlbWFpbCI6WyJnZGUwMDEwN0BuaWZ0eS5jb20iXX0sInNpZ25faW5fcHJvdmlkZXIiOiJwYXNzd29yZCJ9fQ.ABnMA6iOITghzo_WzgdDwssODiLsswVSlKod6w5CHcnkJOQVKqQIynZufTQvcF8nQO77MYXikZD8TQE_uGq3EpHWQibun67mvN74GnPaguzgvpjQ-PqIOzuhnn2n2SpHSacdREtFkwtj1S66bhigbuTJbqr8jQtIEIB6gfmnObwcmpNRsc-GGR45xjWAO6UY4Ygw4xDcHsHGXwL6SA-HbDuSZGeQfXtdPt94taJfrQQB9nr_7gRjttQLz4ongh-g-fMSpWx3z8lmQgPwgg4GyChYPZ6_hdEV3AWFJTHptE2X8RCV6HfpZB6EGwvLQr6ZrC01uodGTg87BvtPrersjA
I've completely no idea of the cause of this panic. Any suggestions are so welcome! Thank you for your suggestions.
As commented by mkopriva, root cause was a reported issue. It's fixed by updating dependencies as follows:
go get -u all
Thank you, mkopriva!
I am trying to send the following data via a POST HTTP request to an API:
{
"client_interface":{
"source_address":source,
"destination_address":destn,
"message":encrypted_msg,
"business_event_url":settings.Message_CallbackURL
},
"server_interface":{
"message_id":msg_id
}
}
The API is responding with the following error:
{
"Meta":{
"Requestid":12301343169471000
},
"Error":{
"Message":"Request body contains badly-formed JSON (at position 51)",
"Param":""
}
}
CODE:
apiUrl := "http://example.com"
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify : true},
}
jsonStr := []byte(`{
"client_interface": {
"source_address": source,
"destination_address": destn,
"message": encrypted_msg,
"business_event_url": settings.Message_CallbackURL
},
"server_interface": {
"message_id": msg_id
}
}`)
req, err := http.NewRequest("POST", apiUrl, bytes.NewBuffer(jsonStr))
fmt.Println("req..........",req)
if err!=nil{
log.Println("err in http req..............",err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("requestid", msg_id)
req.Header.Set("Authorization", "Bearer "+conn_token)
client := &http.Client{Transport: tr}
resp, err := client.Do(req)
if resp!=nil{
body, _ := ioutil.ReadAll(resp.Body)
}
Using struct :
package main
import (
"fmt"
"net/http"
"io/ioutil"
"bytes"
//"crypto/tls"
"encoding/json"
)
type client_interface struct {
source_address string `json:"string"`
destination_address uint64 `json:"uint64"`
message string `json:"string"`
business_event_url string `json:"string"`
}
type server_interface struct {
message_id uint64 `json:"uint64"`
}
type data struct {
client_interface client_interface `json:"client_interface"`
server_interface server_interface `json:"server_interface"`
}
func main() {
url := "https://example.com"
fmt.Println("URL:>", url)
client_interface := client_interface{}
server_interface := server_interface{}
client_interface.source_address="1"
client_interface.destination_address=1111111111
client_interface.message="khsjhdjks"
client_interface.business_event_url="http://callbackurl-hdfc"
server_interface.message_id=8210993557215399651
fmt.Println("server_interface..........",server_interface)
fmt.Println("client_interface..........",client_interface)
body1 := &data{
client_interface: client_interface,
server_interface: server_interface,
}
fmt.Println("body1..........",body1)
t,e:=json.Marshal(body1)
fmt.Println("t..........",t)
fmt.Println("e..........",e)
req, err := http.NewRequest("POST", url, bytes.NewReader(t))
fmt.Println("req......",req)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("requestid", "8210993557215399651")
req.Header.Set("Authorization", "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6IkJCOENlRlZxeWFHckdOdWVoSklpTDRkZmp6dyIsImtpZCI6IkJCOENlRlZxeWFHckdOdWVoSklpTDRkZmp6dyJ9.eyJhdWQiOiJhcGk6Ly90cC1kZXYtdGFubGEtYXBpIiwiaXNzIjoiaHR0cHM6Ly9zdHMud2luZG93cy5uZXQvY2JhYThhYmItZTcwZi00YmI4LWIwNDQtZmZiZjAwNzk0NzkwLyIsImlhdCI6MTU3NTg5MTI3NCwibmJmIjoxNTc1ODkxMjc0LCJleHAiOjE1NzU4OTUxNzQsImFjciI6IjEiLCJhaW8iOiI0MlZnWU9EY3JjenlhZXIxdkRMRDVlNHVtWUxha1UrRUplOVYrZGVlRFgrOTNUMytNRGNBIiwiYW1yIjpbInB3ZCJdLCJhcHBpZCI6IjFmMjI1N2ZlLWIzYjktNGQ2Ny05M2YyLWRjNjM2N2Q2MGM4MCIsImFwcGlkYWNyIjoiMCIsImlwYWRkciI6IjE0LjE0My4xODcuMjUwIiwibmFtZSI6ImhkZmMuMTEiLCJvaWQiOiIzOGQxMGFlNS01OGYyLTQ0NjUtYTFkOC04YTc0NDAzYjc5MmEiLCJzY3AiOiJ1c2VyX2ltcGVyc29uYXRpb24iLCJzdWIiOiIzNDdUd0ZwYUw5MDhmOXlNRWlGOWNHMU84THFQYmJxZk45VzhyQWVEX1prIiwidGlkIjoiY2JhYThhYmItZTcwZi00YmI4LWIwNDQtZmZiZjAwNzk0NzkwIiwidW5pcXVlX25hbWUiOiJoZGZjLjExQFRhbmxhUHJvZHVjdC5vbm1pY3Jvc29mdC5jb20iLCJ1cG4iOiJoZGZjLjExQFRhbmxhUHJvZHVjdC5vbm1pY3Jvc29mdC5jb20iLCJ1dGkiOiJuS05TTXRsT3VFeXMtQjRIOGJ3TEFRIiwidmVyIjoiMS4wIn0.F5H9WCOktau3JaqNyWM91A5jFpJ9eJE99fBWvqDq9kOfCk3OCJnHFKXtIaIA7MoqbxWpNZt1yWpVKuw8gd2Lg_9nfUvvXts2DJHVQN0EqQmFUyWTzhdLW8ZVi6E9RtXK2aEWrI2TVceL5C2wbYOQYfvV4LzjTuNbs6k_20cQ0nD6oO1Id16VVFQWy9yKvpDzsTrvlQdFBZeohIfyL9XWKa8DOk0gxe4bjC7OFmuMsF3FZE5XPaQPHOJ3ejlZJiApml2TlRHnvLpkn1biE3NTAu9aO2lE262lyLg8ZaU0sbPuQaS8P797a-outxLvKEMh07895mA9g6vMxEdRV9X2eA")
client := &http.Client{}
resp, err := client.Do(req)
fmt.Println("err.............",err)
if err != nil {
panic(err)
}
defer resp.Body.Close()
fmt.Println("response Status:", resp.Status)
fmt.Println("response Headers:", resp.Header)
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println("response Body:", string(body))
}
First of all: please use gofmt
Your first code can't work because golang doesn't substitute variables inside string. It's better to use structs.
With structs it's not working because you named struct fields from lower case latter, it means "private" fields in go. So encoding/json package can't access them and just skip them. Use Capital first letters.
Another fix is about 'json:"tag"' - here tag means encoded field name, not type. So instead of 'json:"string"' you should use 'json:"message_id"' or so. You can specify type like this 'json:"field_name,type"' or like this 'json:",type"' but encoding/json guess type on his own.
(I used wrong quotes in tags because of markdown)
I used netcat -l 5000 to listen on 5000 port on localhost and print everything to the terminal. Then I changed url to http://localhost:5000 (not https) to send request to myself.
You need to restart netcat each time to work.
And I made logging a bit more readable.
Also it's CamelCase naming convention in go.
Changed your code a little bit
package main
import (
"bytes"
"flag"
"fmt"
"io/ioutil"
"net/http"
//"crypto/tls"
"encoding/json"
"github.com/nikandfor/tlog"
)
type ClientInterface struct {
SourceAddress string `json:"source_address"`
DestinationAddress uint64 `json:"destination_address"`
Message string `json:"message"`
BusinessEventURL string `json:"business_event_url"`
}
type ServerInterface struct {
MessageID uint64 `json:"message_id"`
}
type Data struct {
ClientInterface ClientInterface `json:"client_interface"`
ServerInterface ServerInterface `json:"server_interface"`
}
var (
// use command line flag. so run like so:
// go run ./file.go -addr https://example.com
addr = flag.String("addr", "http://localhost:5000", "address to send data to")
)
func main() {
flag.Parse() // DO NOT FORGET TO PARSE FLAGS
fmt.Println("URL:>", *addr)
clientInterface := ClientInterface{
SourceAddress: "1",
DestinationAddress: 8886121111,
Message: "khsjhdjks",
BusinessEventURL: "http://callbackurl-hdfc",
}
serverInterface := ServerInterface{
MessageID: 8210993557215399651,
}
tlog.Printf("server_interface %+v", serverInterface)
tlog.Printf("client_interface %+v", clientInterface)
body1 := &Data{
ClientInterface: clientInterface,
ServerInterface: serverInterface,
}
tlog.Printf("body %+v", body1)
t, err := json.Marshal(body1)
if err != nil {
panic(err)
}
tlog.Printf("marshalled: %s", t)
req, err := http.NewRequest("POST", *addr, bytes.NewReader(t))
tlog.Printf("req %v", req)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("requestid", "8210993557215399651")
req.Header.Set("Authorization", "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6IkJCOENlRlZxeWFHckdOdWVoSklpTDRkZmp6dyIsImtpZCI6IkJCOENlRlZxeWFHckdOdWVoSklpTDRkZmp6dyJ9.eyJhdWQiOiJhcGk6Ly90cC1kZXYtdGFubGEtYXBpIiwiaXNzIjoiaHR0cHM6Ly9zdHMud2luZG93cy5uZXQvY2JhYThhYmItZTcwZi00YmI4LWIwNDQtZmZiZjAwNzk0NzkwLyIsImlhdCI6MTU3NTg5MTI3NCwibmJmIjoxNTc1ODkxMjc0LCJleHAiOjE1NzU4OTUxNzQsImFjciI6IjEiLCJhaW8iOiI0MlZnWU9EY3JjenlhZXIxdkRMRDVlNHVtWUxha1UrRUplOVYrZGVlRFgrOTNUMytNRGNBIiwiYW1yIjpbInB3ZCJdLCJhcHBpZCI6IjFmMjI1N2ZlLWIzYjktNGQ2Ny05M2YyLWRjNjM2N2Q2MGM4MCIsImFwcGlkYWNyIjoiMCIsImlwYWRkciI6IjE0LjE0My4xODcuMjUwIiwibmFtZSI6ImhkZmMuMTEiLCJvaWQiOiIzOGQxMGFlNS01OGYyLTQ0NjUtYTFkOC04YTc0NDAzYjc5MmEiLCJzY3AiOiJ1c2VyX2ltcGVyc29uYXRpb24iLCJzdWIiOiIzNDdUd0ZwYUw5MDhmOXlNRWlGOWNHMU84THFQYmJxZk45VzhyQWVEX1prIiwidGlkIjoiY2JhYThhYmItZTcwZi00YmI4LWIwNDQtZmZiZjAwNzk0NzkwIiwidW5pcXVlX25hbWUiOiJoZGZjLjExQFRhbmxhUHJvZHVjdC5vbm1pY3Jvc29mdC5jb20iLCJ1cG4iOiJoZGZjLjExQFRhbmxhUHJvZHVjdC5vbm1pY3Jvc29mdC5jb20iLCJ1dGkiOiJuS05TTXRsT3VFeXMtQjRIOGJ3TEFRIiwidmVyIjoiMS4wIn0.F5H9WCOktau3JaqNyWM91A5jFpJ9eJE99fBWvqDq9kOfCk3OCJnHFKXtIaIA7MoqbxWpNZt1yWpVKuw8gd2Lg_9nfUvvXts2DJHVQN0EqQmFUyWTzhdLW8ZVi6E9RtXK2aEWrI2TVceL5C2wbYOQYfvV4LzjTuNbs6k_20cQ0nD6oO1Id16VVFQWy9yKvpDzsTrvlQdFBZeohIfyL9XWKa8DOk0gxe4bjC7OFmuMsF3FZE5XPaQPHOJ3ejlZJiApml2TlRHnvLpkn1biE3NTAu9aO2lE262lyLg8ZaU0sbPuQaS8P797a-outxLvKEMh07895mA9g6vMxEdRV9X2eA")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
tlog.Printf("response Status: %v", resp.Status)
tlog.Printf("response Headers: %v", resp.Header)
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
panic(err)
}
tlog.Printf("response Body: %s", string(body))
}
$ nc -l 5000
POST / HTTP/1.1
Host: localhost:5000
User-Agent: Go-http-client/1.1
Content-Length: 92
Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6IkJCOENlRlZxeWFHckdOdWVoSklpTDRkZmp6dyIsImtpZCI6IkJCOENlRlZxeWFHckdOdWVoSklpTDRkZmp6dyJ9.eyJhdWQiOiJhcGk6Ly90cC1kZXYtdGFubGEtYXBpIiwiaXNzIjoiaHR0cHM6Ly9zdHMud2luZG93cy5uZXQvY2JhYThhYmItZTcwZi00YmI4LWIwNDQtZmZiZjAwNzk0NzkwLyIsImlhdCI6MTU3NTg5MTI3NCwibmJmIjoxNTc1ODkxMjc0LCJleHAiOjE1NzU4OTUxNzQsImFjciI6IjEiLCJhaW8iOiI0MlZnWU9EY3JjenlhZXIxdkRMRDVlNHVtWUxha1UrRUplOVYrZGVlRFgrOTNUMytNRGNBIiwiYW1yIjpbInB3ZCJdLCJhcHBpZCI6IjFmMjI1N2ZlLWIzYjktNGQ2Ny05M2YyLWRjNjM2N2Q2MGM4MCIsImFwcGlkYWNyIjoiMCIsImlwYWRkciI6IjE0LjE0My4xODcuMjUwIiwibmFtZSI6ImhkZmMuMTEiLCJvaWQiOiIzOGQxMGFlNS01OGYyLTQ0NjUtYTFkOC04YTc0NDAzYjc5MmEiLCJzY3AiOiJ1c2VyX2ltcGVyc29uYXRpb24iLCJzdWIiOiIzNDdUd0ZwYUw5MDhmOXlNRWlGOWNHMU84THFQYmJxZk45VzhyQWVEX1prIiwidGlkIjoiY2JhYThhYmItZTcwZi00YmI4LWIwNDQtZmZiZjAwNzk0NzkwIiwidW5pcXVlX25hbWUiOiJoZGZjLjExQFRhbmxhUHJvZHVjdC5vbm1pY3Jvc29mdC5jb20iLCJ1cG4iOiJoZGZjLjExQFRhbmxhUHJvZHVjdC5vbm1pY3Jvc29mdC5jb20iLCJ1dGkiOiJuS05TTXRsT3VFeXMtQjRIOGJ3TEFRIiwidmVyIjoiMS4wIn0.F5H9WCOktau3JaqNyWM91A5jFpJ9eJE99fBWvqDq9kOfCk3OCJnHFKXtIaIA7MoqbxWpNZt1yWpVKuw8gd2Lg_9nfUvvXts2DJHVQN0EqQmFUyWTzhdLW8ZVi6E9RtXK2aEWrI2TVceL5C2wbYOQYfvV4LzjTuNbs6k_20cQ0nD6oO1Id16VVFQWy9yKvpDzsTrvlQdFBZeohIfyL9XWKa8DOk0gxe4bjC7OFmuMsF3FZE5XPaQPHOJ3ejlZJiApml2TlRHnvLpkn1biE3NTAu9aO2lE262lyLg8ZaU0sbPuQaS8P797a-outxLvKEMh07895mA9g6vMxEdRV9X2eA
Content-Type: application/json
Requestid: 8210993557215399651
Accept-Encoding: gzip
{"client_interface":{"source_address":"1","destination_address":8886121111,"message":"khsjhdjks","business_event_url":"http://callbackurl-hdfc"},"server_interface":{"message_id":8210993557215399651}}
Is it what you've expected?
And the last. I strongly suggest you to read https://golang.org/doc/effective_go.html
I try to parse a page with this code :
client := &http.Client{}
profile := getEpiURL(login)
log.Print("Fetch " + profile)
req, err := http.NewRequest("GET", profile, nil)
if err != nil {
log.Fatal(err)
}
req.AddCookie(cookieSessionIntra)
body, _ := httputil.DumpRequestOut(req, true)
With this as getEpiURL function :
func getEpiURL(login string) (url string) {
url = "https://********/user/" + login + "/?format=json"
return
}
And when i look at the output the profile variable is good, but in the Request it seems obviously wrong...
2016/11/24 12:53:53 Fetch https://********/user/le****in-vi**rd#e*******/?format=json
Then the debug for the request prints me :
GET /user/%00l%*****0o%*00.%00c***0-%00v%00i%0*a%00r%00d%00#%00e%00i%00t%00e%00c%0***0.%0***00/?format=json
HTTP/1.1 Host: ****** User-Agent: Go-http-client/1.1 Cookie:
PHPSESSID=********* Accept-Encoding: gzip
I think your original string somehow contains NUL characters. Try this out in the playground:
func main() {
req, err := http.NewRequest("GET", "https://some/normal/path", nil)
if err != nil {
log.Fatal(err)
}
body, _ := httputil.DumpRequestOut(req, true)
fmt.Printf("Hello, playground, %q", body)
}
You'll get:
"GET /normal/path HTTP/1.1\r\nHost: some...
Now try it with a string in which you inserted NUL characters:
req, err := http.NewRequest("GET", "https://some/\000n\000o\000rmal/path", nil)
...
"GET /%00n%00o%00rmal/path HTTP/1.1\r\nHost: some...
Not quite sure how your string ended up containing those. Read more about percent encoding.