Infinite redirect loop with Gorilla toolkit - go

I have this simple code:
import (
"log"
"github.com/gorilla/http"
"bytes"
)
func main() {
url := "https://www.telegram.org"
log.Println("url: " + url)
var b bytes.Buffer
http.Get(&b, url)
log.Println("Get done")
}
and it freezes on the line making the GET request. It seems that it enters an infinite loop of 302 responses which redirects to the same url ("https://www.telegram.org").
Am I doing or assuming something wrong?
Thanks and regards.

Apparently that library doesn't support https (lol)
https://github.com/gorilla/http/issues/8
So just use the stdlib http module:
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func main() {
res, err := http.Get("https://www.telegram.org")
if err != nil {
return
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return
}
fmt.Printf("%s", body)
}

Related

Output and meaning of PostForm requests in Go

In the code below, I am serving a PostForm request, and when I run the code I am getting an output of Age=20&Name=Mike, instead of a map like {"Name":Mike,"Age":"20"}. Is that output appropriate or am I missing something?
Also what is the difference between a PostForm request and a Post request?
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
)
func server() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
content, _ := ioutil.ReadAll(r.Body)
fmt.Println(string(content))
})
log.Fatal(http.ListenAndServe("", nil))
}
func client() {
data := url.Values{}
data.Add("Name", "Mike")
data.Add("Age", "20")
response, err := http.PostForm("http://localhost/", data)
if err != nil {
return
}
defer response.Body.Close()
}
func main() {
go server()
client()
}

How can I check specific golang net/http error code?

package main
import "net/http"
func main() {
req, err := http.NewRequest("GET", "http://domain_does_not_exist", nil)
if err != nil { panic("NewRequest") }
client := http.Client{ }
_, err = client.Do(req)
if err == ???
}
I would like to check my GET request for specific error(DNS resolve error). How to accomplish this?
Package "errors" has functions As, Is to unwrap specific error types, and package "net" has a *DNSError type. So:
var dnsErr *net.DNSError
if errors.As(err, &dnsErr) {
...
}

Why after I run my code , appear undefined:returnAllSMSBlasts , so my function not working why?

I Make Restful api , I want display result , but golang say error about function , error say "undefined: returnAllSMSBlasts" why , can you check my code error ?
this my code
data.go
package main
import (
"encoding/json"
"log"
"net/http"
)
func returnAllSMSBlasts(w http.ResponseWriter, r *http.Request) {
var smsblasts SMSBlasts
var arr_smsblast []SMSBlasts
var response Response
db := connect()
defer db.Close()
rows, err := db.Query("Select SequenceID,MobilePhone,Output,WillBeSentDate,SentDate,Status,DtmUpd")
if err != nil{
log.Print(err)
}
for rows.Next(){
if err := rows.Scan(&smsblasts.SequenceID, &smsblasts.MobilePhone,
&smsblasts.Output, &smsblasts.WillBeSentDate,
&smsblasts.SentDate, &smsblasts.Status,
&smsblasts.DtmUpd); err != nil{
log.Fatal(err.Error())
}else{
arr_smsblast = append(arr_smsblast , smsblasts)
}
}
response.Status = 1
response.Message = "success"
response.Data = arr_smsblast
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(response)
}
and this my code
main.go
package main
import (
"fmt"
"log"
"net/http"
"github.com/gorilla/mux"
_ "github.com/denisenkom/go-mssqldb"
)
func main() {
router := mux.NewRouter()
router.HandleFunc("/postsmsblasts", returnAllSMSBlasts).Methods("POST")
http.Handle("/", router)
fmt.Println("Connected to port 1234")
log.Fatal(http.ListenAndServe(":1234", router))
}

Understanding mux router in golang

here is my code trying to display a base64 image it worked before using mux.
I've used http handlefunc before using mux, here i want to use mux and get the value of key.
package main
import (
"fmt"
"net/http"
"strconv"
base64 "encoding/base64"
"log"
"io"
"io/ioutil"
"os"
"github.com/gorilla/mux"
)
var (
Trace *log.Logger
Info *log.Logger
Warning *log.Logger
Error *log.Logger
)
func Init(
traceHandle io.Writer,
infoHandle io.Writer,
warningHandle io.Writer,
errorHandle io.Writer) {
Trace = log.New(traceHandle,
"TRACE: ",
log.Ldate|log.Ltime|log.Lshortfile)
Info = log.New(infoHandle,
"INFO: ",
log.Ldate|log.Ltime|log.Lshortfile)
Warning = log.New(warningHandle,
"WARNING: ",
log.Ldate|log.Ltime|log.Lshortfile)
Error = log.New(errorHandle,
"ERROR: ",
log.Ldate|log.Ltime|log.Lshortfile)
}
func get_info(r *http.Request){
fmt.Println(r.RemoteAddr)
fmt.Println(r.Header.Get("x-forwarded-for"))
fmt.Println(r.UserAgent())
fmt.Println(r.Referer())
}
func pix(w http.ResponseWriter, r *http.Request) {
Info.Println("Hi there, I love %s!", r.URL.Path[1:])
vars := mux.Vars(r)
key := vars["key"]
Info.Println("key", key)
var cookie *http.Cookie
cookie , err := r.Cookie("csrftoken")
if (err != nil ){
fmt.Printf("error")
fmt.Println(err)
}
get_info(r)
fmt.Printf(cookie.Value)
w.Header().Set("Content-Type", "image/jpeg")
p, err := base64.StdEncoding.DecodeString("iVBORw0KGgoAAAANSUhEUgAAADIAAAAyCAIAAACRXR/mAAADMUlEQVRYw+2YTUgUYRjHZzOJIoNA+rrUyYNIRQgRHaLo4qFDBEGeunSxS9TFU0QEnhIh6IvokrUzO2uamRmbG6XmR/mVaKZpZVbYvvO143zszsxOz+yahNm+785sITEP72F3Z+adH8/zf5+PpagwtxKXj+Vj+Vg+lo/lY+W+WI4KpddKwWIQFUSF97nNLcLGZt75SiOHchEXfskDVmYjlowpiEoei3UT2ljcFJOpOd169C1Z2SuvgsdpB7cgzB16EV/byGM2xDIVPxQujKmBDF/2m2l0vFvmEin7N2v8kiiPiOeGlGHRvP1RdxA9eYtGR7pk2Pf6lI7RCoP2RaWkZWe3fsFc18hvesAHPGEFUc24ltnx3kyiCJwfRMs6dTXLdSIjO9Osal18qzKfE5V9coDxhlU7qS3uOyiaB55JDtkS2TKoLCLaOLPS4b02pQdCHiUfRKf653/d2kjZN6f10jYxI2EnrGk5H+2WsVi6ZZ8fVSmGQKaYyyFuR6ugmUtVrJo2C7HokeGq8447sYpOPBbo3XFzKC95626sZlz905sUM9XLGbXvtKtTOhZrQDApkhNNkiAOPo/viojh2YSZsj1aF2eQ5n2stuomNQjiiGQanrFufdCXP8gu8tbhjridJ6saVPKExXJrwlwfb3pnAg2Ut0tEBZFI8gza81Tik15DCDIoINQ7aQdBo90RMfrdwNaWLFY9opJGkBQrhCA/HXspQ8W1XHkN6vfWFiGH9ouwhdpJUFuy2JX3eg6uyqENpNHZYcUd02jcLMI2WO67UwZVv1G1HLMq3L83KuEbLPdY7IL2L42p0MMQiuzkq/ncwucOi6qPbWkWoPfCUsENpweUnP1EmE4XGhgagT72RyXolkSCHBbTU3By3fgJj8VyJW3CmSHl8oTWMJuYUUizVvtcsuyJ6J4J663CMLevXar/lJgnKNSgbphzKjriTn5i0F8eX9ODXnEzf6JHvjGtv+aNGdWCOEKnJRmpr5oFVQV8WTWglIKHMlPhv5uqQ1xGYfB5fRMPo+n2VmFbi7ChiS9oWBhZvXrI01TNLg7yPxt51v9rxMfysXwsH8vH+g+wfgDUr+5LcyNV4AAAAABJRU5ErkJggg==")
if err != nil {
http.Error(w, "internal error", 500)
return
}
w.Header().Set("Content-Length", strconv.Itoa(len(p))) //len(dec)
w.Write(p)
}
func main() {
Init(ioutil.Discard, os.Stdout, os.Stdout, os.Stderr)
Info.Println("1")
r := mux.NewRouter()
Info.Println("2")
r.HandleFunc("/pix/{key}/pixel.gif", pix)
err := http.ListenAndServe(":9080", nil)
Info.Println("3")
if err != nil {
fmt.Println(err)
}
}
It seems that when i call http://localhost:9080/pix/2/pixel.gif
it doesn't call pix.
the url for calling it seems correct
any idea why ?
regards and thanks
It appears that you are not assigning r to anything, you should add the following at the end of your main:
http.Handle("/", r)

malformed HTTP status code "/" error in Go

Server.go
package main
import (
"fmt"
"net/http"
//"strings"
"encoding/json"
"io/ioutil"
"strconv"
"net"
"bufio"
)
type Message struct {
Text string
}
func Unmarshal(data []byte, v interface{}) error
func main() {
//http.HandleFunc("/", handler)
server,_ := net.Listen("tcp", ":" + strconv.Itoa(8080))
if server == nil {
panic("couldn't start listening: ")
}
conns := clientConns(server)
for {
go handleConn(<-conns)
}
}
func clientConns(listener net.Listener) chan net.Conn {
ch := make(chan net.Conn)
i := 0
go func() {
for {
client, _ := listener.Accept()
if client == nil {
fmt.Printf("couldn't accept: ")
continue
}
i++
fmt.Printf("%d: %v <-> %v\n", i, client.LocalAddr(), client.RemoteAddr())
ch <- client
}
}()
return ch
}
func handleConn(client net.Conn) {
b := bufio.NewReader(client)
fmt.Println("Buffer")
for {
line, err := b.ReadBytes('\n')
if err != nil { // EOF, or worse
break
}
client.Write(line)
}
}
Client.go
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"strings"
"flag"
//"io"
// "net"
// "net/rpc"
// "sync"
)
func Unmarshal(data []byte, v interface{}) error
func Marshal(v interface{}) ([]byte, error)
type Message struct {
Text string
}
func main(){
var flagtext = flag.String("flagtext", "Hello!", "Flag")
flag.Parse()
var text string
text = *flagtext
m := Message{text}
var m1 Message
b, err := json.Marshal(m)
if err == nil{
resp, err := http.Post("http://127.0.0.1:8080","application/json", strings.NewReader(string(b)))
if err != nil{
log.Fatal("Error while post: %v",err)
}
fmt.Println(resp)
err = json.Unmarshal(b, &m1)
}
}
Error I get when I run client.go is this:
Error while post: %vmalformed HTTP status code "/"
Though, the server registers a channel for each post, it shows a malformed HTTP status code. Is it because I'm listening in the wrong channel? I'm confused why this error is occurring.
This line in the server code:
client.Write(line)
sends the request line back to the client. Since the client is posting something like GET / HTTP/1.1, this means that the server is responding with something like GET / HTTP/1.1, instead of something like HTTP/1.1 200 OK. The error-message you're seeing is because / appears in the status-code position.
In server.go it seems you are trying to write your own HTTP server from the TCP socket level up. This is unnecessary work - take the easy route and use the built-in HTTP server API.
The general outline of such a server is like this:
package main
import (
"fmt"
"net/http"
)
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:])
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":8080", nil)
}
and is described further in this article. More documentation is in net/http.

Resources