Redirect http to https when get: Client sent an HTTP request to an HTTPS server

How can I put custom handle in this case: client sent HTTP request to HTTPS server
I want redirect to https.

2 Likes

Hi kamil
u can use mux, as our friend Johandalabacka said :

2 Likes

it’s not a solution
I have one https server and one port open
https://gist.github.com/denji/12b3a568f092ab951456
example:

package main

import (
    // "fmt"
    // "io"
    "net/http"
    "log"
)

func HelloServer(w http.ResponseWriter, req *http.Request) {
    w.Header().Set("Content-Type", "text/plain")
    w.Write([]byte("This is an example server.\n"))
    // fmt.Fprintf(w, "This is an example server.\n")
    // io.WriteString(w, "This is an example server.\n")
}

func main() {
    http.HandleFunc("/hello", HelloServer)
    err := http.ListenAndServeTLS(":8081", "server.crt", "server.key", nil)
    if err != nil {
        log.Fatal("ListenAndServe: ", err)
    }
}

and when i open:

http://localhost:8081/hello

i need redirect to :

https://localhost:8081/hello

because i get:

Client sent an HTTP request to an HTTPS server.

2 Likes

Hi

You can’t have both http and https on the same port (at least not with the http library functions in go). On webservers is usually http on port 80 and https on port 443. So open two different servers and use

Redirect(w ResponseWriter, r *Request, url string, code int)

To redirect all calls on the http server to the one running https

2 Likes

Ok… True… you’re right. My mistake…

But I was hoping that this is possible… because information about the bad protocol was sent via http.

For example, if I want to change the error message to make it look different.
Maybe it would be possible to throw a redirect there …

But that’s stupid. Sorry.

2 Likes

Not stupid. Don’t apologize for learning.
Others with the same question will benefit from this thread.

2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.