Configuring http:localhost for Golang [duplicate] - http

This question already has answers here:
Run go web application on IIS
(2 answers)
Closed 4 years ago.
I would like to realize some tutorials in Golang which covers net/http library and other web and routing libraries as well. Besides, I use my localhost to test my asp.net core with IIS. I have already stopped my IIS client on my machine and it still redirects me to IIS themed localhost instead of showing my golang Fprintf message.The page on my localhost, my current iis settings, and the golang code can be seen below. Any help would be appreciated.
The page on http:localhost
My IIS situation summary(It is stopped manually)
package main
import "fmt"
import "net/http"
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
numOfBytesWritten, err := fmt.Fprintf(w, "Hello, World!")
if err != nil {
fmt.Fprintln(w, "Error occured!")
}
fmt.Fprintln(w, numOfBytesWritten, " bytes written.")
http.ListenAndServe(":80", nil)
})
}
My sites on ISS.

My mistake was silly :)
http.ListenAndServe(":80", nil)
line should not be inside http.HandleFunc(). So my final code is below and it works as expected.
package main
import (
"fmt"
"net/http"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
n, err := fmt.Fprintf(w, "Hello World!\n")
if err == nil {
fmt.Fprintf(w, "%d bytes written\n", n)
} else {
fmt.Fprintf(w, "Error occured.")
}
})
http.ListenAndServe(":80", nil)
}

Make sure Default Web Site is not running, looks like you stopped something else.
See the attached image. https://i.stack.imgur.com/OMhjP.png

Related

Set base path for follow-up HTTP request

Suppose there is a file called foo.html and a project structure that looks like this:
|--styles
| |--style.css 📜
|--pages
| |--foo.html 📜
foo.html contains (among other stuff):
<link rel="stylesheet" type="text/css" href="styles/style.css">
Now, when the client requests for pages/foo.html, it will see the link to the css file and it will make a follow-up request to pages/styles/style.css. Is there a way I can instead tell it from the file server to make a request to styles/style.css rather than pages/styles/style.css?
I'm using the Go http library from the standard library.
I guess you are already using http go package. Here is the below sample code which can help you to achieve what you intend to do:
package main
import (
"fmt"
"log"
"net/http"
)
func hello(w http.ResponseWriter, req *http.Request) {
fmt.Fprintf(w, "hello1\n")
}
func main() {
fs := http.FileServer(http.Dir("./page/static"))
http.Handle("/page/styles/", http.StripPrefix("/page/styles/", fs))
page_fs := http.FileServer(http.Dir("./page"))
http.Handle("/page/", http.StripPrefix("/page/", page_fs))
http.HandleFunc("/hello", hello)
log.Println("Listening on :3000...")
err := http.ListenAndServe(":3000", nil)
if err != nil {
log.Fatal(err)
}
}
Let me know if you need explanation.

Why the first request to video server did not return bytes data of the video

I wrote a simple video server as follow:
package main
import (
"log"
"net/http"
"os"
"time"
)
func ServeHTTP(w http.ResponseWriter, r *http.Request) {
video, err := os.Open("/Users/icheer/Downloads/jsc/jsc.mp4")
if err != nil {
log.Fatal(err)
}
defer video.Close()
http.ServeContent(w, r, "jsc.mp4", time.Now(), video)
}
func main() {
http.HandleFunc("/", ServeHTTP)
_ = http.ListenAndServe(":8080", nil)
}
It works well, but I am curious about what chrome do when I open http://localhost:8080 in chrome.
Why the first request status code is 200, but the 'Time' is 'Pending', what 'Pending' exactly mean? How did chrome know the request show 'Pending'? And what confused me most is, i do not know which line of my golang code result in that. As the source code net/http/fs.go shows,
the sendSize is the total length of the video 5357093240, so I think the first request should return all bytes data of the video , but in fact, the response Size is 177B as the first picture shows, I do not know which line of the golang code result in that.

Unable to read post form value in Golang with htprouter

I'm new to Golang and trying to get a basic http app running using the httprouter API. I've hit a wall with reading posted form data, despite following the advice given in another StackOverflow question.
Here's my code (minus irrelevancies):
import (
"fmt"
"net/http"
"github.com/julienschmidt/httprouter"
)
func main() {
r := httprouter.New()
r.POST("/sub", func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
r.Header.Set("content-type", "text/html")
err := r.ParseForm()
if err != nil {
fmt.Fprintf(w, "<h1>Error: %s</h1>\n", err)
}
fmt.Fprintf(w, "<h1>Submitted message!</h1>\n<p>-%s-</p>\n", r.PostFormValue("msg"))
})
http.ListenAndServe("localhost:3000", r)
}
In the output, where I should see -hello-, I just see --. When I inspect the http request in Firefox, in the Form Data panel, I see msg:"hello", so why is r.PostFormValue("msg") returning a blank string?
Thanks to Volker for pointing out an error. When I commented out the line r.Header.Set("content-type", "text/html"), the problem was resolved. Perhaps that was the issue, or perhaps there was some issue with the IDE (LiteIDE) caching an old version of the code. In any case, I can now read the posted value.

Golang: Why does response.Get("headerkey") not return a value in this code?

This has been bothering me for the past couple hours, I'm trying to get a response header value. Simple stuff. If I curl a request to this running server, I see the header set, with curl's -v flag, but when I try to retrieve the header using Go's response.Header.Get(), it shows a blank string "", with the header's length being 0.
What frustrates me even more, is that the header value is actually set within the response when I print out the body (as demonstrated below).
Any and all help with this is appreciated, thanks in advance.
I have this code here:
http://play.golang.org/p/JaYTfVoDsq
Which contains the following:
package main
import (
"fmt"
"io/ioutil"
"net/http"
"net/http/httptest"
)
func main() {
mux := http.NewServeMux()
server := httptest.NewServer(mux)
defer server.Close()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
r.Header.Set("Authorization", "responseAuthVal")
fmt.Fprintln(w, r.Header)
})
req, _ := http.NewRequest("GET", server.URL, nil)
res, _:= http.DefaultClient.Do(req)
headerVal := res.Header.Get("Authorization")
fmt.Printf("auth header=%s, with length=%d\n", headerVal, len(headerVal))
content, _ := ioutil.ReadAll(res.Body)
fmt.Printf("res.Body=%s", content)
res.Body.Close()
}
The output to this running code is:
auth header=, with length=0
res.Body=map[Authorization:[responseAuthVal] User-Agent:[Go-http-client/1.1] Accept-Encoding:[gzip]]
This line:
r.Header.Set("Authorization", "responseAuthVal")
set the value of r *http.Request, that is the incomming request, while you want to set the value of w http.ResponseWriter, the response that you will receive.
The said line should be
w.Header().Set("Authorization", "responseAuthVal")
See this playgroud.

Unexpected EOF using Go http client

I am learning Go and came across this problem.
I am just downloading web page content using HTTP client:
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
)
func main() {
client := &http.Client{}
req, err := http.NewRequest("GET", "https://mail.ru/", nil)
req.Close = true
response, err := client.Do(req)
if err != nil {
log.Fatal(err)
}
defer response.Body.Close()
content, err := ioutil.ReadAll(response.Body)
if err != nil {
fmt.Println(err)
}
fmt.Println(string(content)[:100])
}
I get an unexpected EOF error when reading response body. At the same time content variable has full page content.
This error appear only when I downloading https://mail.ru/ content. With other URLs everything works fine - without any errors.
I used curl for downloading this page content - everything works as expected.
I am confused a bit - what's happening here?
Go v1.2, tried on Ubuntu and MacOS X
It looks like the that server (Apache 1.3, wow!) is serving up a truncated gzip response. If you explicitly request the identity encoding (preventing the Go transport from adding gzip itself), you won't get the ErrUnexpectedEOF:
req.Header.Add("Accept-Encoding", "identity")

Resources