I'm new to Golang, Angular (7.1.4), and websockets. I'm following this tutorial strictly to learn them, and everything runs as expected. However, I don't understand how Angular serves the chat room page at localhost:4200/*, where * can be anything I type.
Edit: my primary question is, how does this happen given that the only place where I've affected the URL at all seems to be in this line this.socket = new WebSocket("ws://localhost:12345/ws")
in socket.service.ts in the Angular project. I think this means the page should load only on localhost:4200, if anywhere.
I read some of Angular's documentation, and the closest I've come to an answer is on its page on routing, where it says "The ** path in the last route is a wildcard. The router will select this route if the requested URL doesn't match any paths for routes defined earlier in the configuration." But I've not used **
anywhere. In fact, I've not used routing at all following the tutorial.
Here is the full socket.service.ts file:
import { Injectable } from "@angular/core";
import { EventEmitter } from "@angular/core";
@Injectable({
providedIn: "root"
})
export class SocketService {
private socket: WebSocket;
private listener: EventEmitter<any> = new EventEmitter();
public constructor() {
# I think only this line is used to manage the URL.
this.socket = new WebSocket("ws://localhost:12345/ws");
this.socket.onopen = event => {
this.listener.emit({ type: "open", data: event });
};
this.socket.onclose = event => {
this.listener.emit({ type: "close", data: event });
};
this.socket.onmessage = event => {
this.listener.emit({ type: "message", data: JSON.parse(event.data) });
};
}
public send(data: string) {
this.socket.send(data);
}
public close() {
this.socket.close();
}
public getEventListener() {
return this.listener;
}
}
In main.go in Golang, only two lines, and primarily http.HandleFunc("/ws", wsPage)
, relate to the chat room URL. Based on this, I assumed that the page can also load on localhost:12345/ws. But going there produces "Bad Request 404 page not found". Here is the code I think is relevant from main.go:
func wsPage(res http.ResponseWriter, req *http.Request) {
conn, error := (&websocket.Upgrader{CheckOrigin: func(r *http.Request) bool { return true }}).Upgrade(res, req, nil)
if error != nil {
http.NotFound(res, req)
return
}
client := &Client{id: uuid.NewV4().String(), socket: conn, send: make(chan []byte)}
manager.register <- client
go client.read()
go client.write()
}
func main() {
go manager.start()
# Only these two lines relate to the URL.
http.HandleFunc("/ws", wsPage)
http.ListenAndServe(":12345", nil)
}
Can someone explain how Angular manages URLs in this instance and how its URL takes precedence over Golang's? Or point me to the right documentation/reading material? Thanks.