ChatGPT に言ってもらったほうが説得力がある…(;_;)
UTF-8 文字列を含む response.statusText を JavaScript で文字列にデコードするメモ / Decode UTF-8 string within response.statusText to string with JavaScript
PHP で statusText に日本語 UTF-8 を入れて javascript へ送り返したところ…読めない
忘れそうなのでメモ
1 |
const statusText = decodeURIComponent(escape(response.statusText)); |
element の位置やサイズを小数点以下まで取得したい時
element.getBoundingClientRect()
—
React.js で Hooks でも JSX したくない時 / If don’t want to use JSX in React.js Hooks too.
index.js:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
// import React, { useState } from 'react' // const Context = React.createContext({ foo: 0, bar: 1 }, () => { }); const Context = React.createContext(); const Grandchild2 = () => { const e = React.createElement; return e(Context.Consumer, {}, value => { return e("div", {}, e("p", {}, `Grandchild2 ${value.values.bar}`), e("button", { onClick: () => value.setCount({ ...value.values, foo: value.values.foo + 100 }), }, "Click"), ); }); }; const Grandchild1 = () => { const e = React.createElement; const value = React.useContext(Context); // console.log(value); return e("p", {}, `Grandchild1 ${value.values.foo}`); }; const Child = () => { const e = React.createElement; return e("div", {}, [ e(Grandchild1, { key: 1 }), e(Grandchild2, { key: 2 }), ]); }; const App = () => { // console.log("App"); const e = React.createElement; // const Context = React.createContext(); const [values, setCount] = React.useState({ foo: 0, bar: 1 }); // console.log(values); // Similar to componentDidMount and componentDidUpdate: React.useEffect(() => { // Update the document title using the browser API document.title = `You clicked ${values.foo} times`; }); return ( e(Context.Provider, { value: { values: values, setCount: setCount } }, e("p", {}, `Count: ${values.foo}, ${values.bar}`), e("button", { onClick: () => setCount({ foo: values.foo + 1, bar: values.bar + 1 }), }, "Click"), e(Child), ) ); }; // export default App |
index.html:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Hooks</title> <script src="./js/lib/react.development.js"></script> <script src="./js/lib/react-dom.development.js"></script> </head> <body> <div id="root"></div> <script src="./js/index.js"></script> <script> (function () { const e = React.createElement; ReactDOM.render(e(App), document.getElementById("root")); })(); </script> </body> </html> |
特に普通(?)だった。
React.js で JSX したくない時 / If don’t want to use JSX in React.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 |
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>If don't want to use JSX</title> </head> <body> <div class="container"> <div id="root"> <p>Wait...</p> </div> <div> <button onclick="getValue();">Output value to console</button> </div> </div> <script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script> <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script> <script> const e = React.createElement; // コンポーネントの定義 class MyComponent extends React.Component { constructor(props, context, updater) { super(props, context, updater); console.log("props", props); console.log("context", context); console.log("updater", updater); this.state = { updatable: false, value: props.value, // initial value count: props.value.length, // status: props.status, }; } render() { return e("div", { ...this.props }, // Set name, className and ... e("input", { type: "text", value: this.state.value, // initial value onChange: this.cbOnChange, // change value }, ), e("span", null, this.state.count), e("span", null, this.state.error), ); } componentDidUpdate(event) { console.log("componentDidUpdate", this.state); } componentDidMount() { console.log("mounted"); } cbOnChange = (event) => { this.setState({ value: event.target.value }); this.setState({ count: event.target.value.length }); console.log(this.props.value); return false; } } // コンポーネントの定義 2 class MyComponentTextarea extends React.Component { constructor(props, context, updater) { super(props, context, updater); console.log("props", props); console.log("context", context); console.log("updater", updater); this.state = { updatable: false, value: props.value, // initial value count: props.value.length, // status: props.status, }; } render() { return e("div", { ...this.props }, // Set name, className and ... e("textarea", { value: this.state.value, // initial value onChange: this.cbOnChange, // change value }, ), e("span", null, this.state.count), e("span", null, this.state.error), ); } componentDidUpdate(event) { console.log("componentDidUpdate", this.state); } componentDidMount() { console.log("mounted"); } cbOnChange = (event) => { this.setState({ value: event.target.value }); this.setState({ count: event.target.value.length }); console.log(this.props.value); return false; } } // コンポーネントの定義 3 class MyComponentSelect extends React.Component { constructor(props, context, updater) { super(props, context, updater); console.log("props", props); console.log("context", context); console.log("updater", updater); this.state = { updatable: false, value: props.value, records: props.records, // initial value status: props.status }; } render() { let options = this.props.records.map(function (record, index) { // console.log("record", record, "index", index); return ( e("option", { key: index, value: record[0] }, record[1]) ); }); return e("div", { ...this.props }, // Set name, className and ... e("select", { type: "text", value: this.state.value, // initial value onChange: this.cbOnChange, // change value }, options, ), e("span", null, this.state.count), ); } componentDidUpdate(event) { console.log("componentDidUpdate", this.state); } componentDidMount() { console.log("componentDidMount"); } cbOnChange = (event) => { this.setState({ value: event.target.value }); console.log(this.props.value); } } this.refs = Array(); this.refs["input-text-1"] = React.createRef(); this.refs["input-text-2"] = React.createRef(); this.refs["textarea-1"] = React.createRef(); this.refs["select-1"] = React.createRef(); getValue = () => { console.log("getValue"); console.log(this.refs["input-text-1"].current.state.value); console.log(this.refs["input-text-2"].current.state.value); console.log(this.refs["textarea-1"].current.state.value); console.log(this.refs["select-1"].current.state.value); } // validation handleChange = (field, event) => { event.persist(); // console.log(field, event); const value = event.target.value; // console.log("value", value); // console.log(event.currentTarget); const current = this.refs[field].current; // console.log("current", current); switch (field) { case "input-text-1": case "input-text-2": if (value == "abc") { current.setState({ error: "" }); } else { current.setState({ error: "error" }); } break; case "textarea-1": if (value == "abc") { current.setState({ error: "" }); } else { current.setState({ error: "error" }); } break; default: } } const el = e("div", { className: "class1" }, e("p", {}, "Test"), e(MyComponent, { ref: this.refs["input-text-1"], className: "class2", value: "Test 123", onChange: this.handleChange.bind(this, "input-text-1") }), e(MyComponent, { ref: this.refs["input-text-2"], className: "class2", value: "default value", onChange: this.handleChange.bind(this, "input-text-2") }), e(MyComponentTextarea, { ref: this.refs["textarea-1"], name: "textarea-1", className: "class4", value: "default value....", onChange: this.handleChange.bind(this, "textarea-1") }), e(MyComponentSelect, { ref: this.refs["select-1"], className: "class3", value: 2, records: [ [1, "aa"], [2, "bb"], [3, "cc"], ] }), ); ReactDOM.render(el, document.getElementById("root")); </script> </body> <!-- https://www.youtube.com/watch?v=xJAqa0U_X50 https://getbootstrap.com/ https://reactjs.org/docs/add-react-to-a-website.html https://the2g.com/2796 https://stackoverflow.com/questions/41296668/reactjs-form-input-validation --> </html> |
WebSocket を Golang でどうやったらいいか試してみた / WebSocket Test with Golang and Javascript
Chat サーバーを作ってみた…こぴぺしてみた
main.go:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 |
package main import ( "fmt" "html" "log" "net/http" "time" "golang.org/x/net/websocket" ) var websocketList map[string]*websocket.Conn type message struct { Msg string } func auth(w http.ResponseWriter, req *http.Request) (string, error) { c, err := req.Cookie("X-User") if err != nil { return "", err } user := c.Value if len(user) == 0 { websocket.Handler(func(ws *websocket.Conn) { websocket.JSON.Send(ws, message{"Authentication failed"}) }).ServeHTTP(w, req) return "", fmt.Errorf("Authentication failed") } return user, nil } func main() { log.Println("Start main") websocketList = map[string]*websocket.Conn{} http.Handle("/", http.FileServer(http.Dir("./"))) http.HandleFunc("/chat", func(w http.ResponseWriter, req *http.Request) { user, err := auth(w, req) if err != nil { return } prepared := make(chan bool) go func() { <-prepared sendToEveryone(user + " logged in") }() s := websocket.Server{Handler: func(conn *websocket.Conn) { // Want to know way to get Conn websocketList[user] = conn prepared <- true log.Println("conn.MaxPayloadBytes", conn.MaxPayloadBytes) chatHandler(user, conn) }} s.ServeHTTP(w, req) // blocking... log.Println("--") delete(websocketList, user) }) if err := http.ListenAndServe(":9000", nil); err != nil { panic("ListenAndServe: " + err.Error()) } } func sendToEveryone(msg string) { for _, w := range websocketList { t := time.Now() d := t.Format("Monday Jan 02 15:04:05 JST 2006") // d := t.Format("2006-01-02 15:04:05") // => "2015-05-05 07:53:54" websocket.JSON.Send(w, message{fmt.Sprintf("%s / %s", html.EscapeString(msg), d)}) } } func chatHandler(user string, conn *websocket.Conn) { log.Println("chatHandler") for { var msg message if err := websocket.JSON.Receive(conn, &msg); err != nil { log.Println(err) break } sendToEveryone(user + " ⇒ " + msg.Msg) } } |
websocket.js:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 |
// var wsUri = "ws://localhost:9999/chat"; var wsUri = "ws://" + location.host + "/chat"; var output; var websocket; function init() { output = document.getElementById("output"); } function login() { var user = document.getElementById("user").value; document.cookie = 'X-User=' + user + '; path=/'; websocket = new WebSocket(wsUri); websocket.onopen = function (event) { onOpen(event) }; websocket.onclose = function (event) { onClose(event) }; websocket.onmessage = function (event) { onMessage(event) }; websocket.onerror = function (event) { onError(event) }; } function send() { var msg = document.getElementById("msg").value; // writeToScreen(msg); doSend(msg); } function onOpen(event) { writeToScreen("CONNECTED"); document.getElementById("login").style.display = "none"; document.getElementById("send").style.display = "initial"; } function onClose(event) { // console.log(event); writeToScreen("DISCONNECTED"); writeToScreen('<span style="color: blue;">CLOSE: ' + getWebSocketErrorMessage(event.code) + '</span>'); document.getElementById("login").style.display = "initial"; document.getElementById("send").style.display = "none"; } function onMessage(event) { var jsonData = JSON.parse(event.data) // console.log(jsonData) writeToScreen('<span style="color: black;">' + jsonData.Msg + '</span>'); // websocket.close(); } function onError(event) { // console.log(event); writeToScreen('<span style="color: red;">ERROR:</span>'); } function doSend(message) { var jsonData = { Msg: message, } websocket.send(JSON.stringify(jsonData)); } function writeToScreen(message) { var pre = document.createElement("p"); pre.style.wordWrap = "break-word"; pre.innerHTML = message; // output.appendChild(pre); output.prepend(pre) } // https://stackoverflow.com/questions/18803971/websocket-onerror-how-to-read-error-description function getWebSocketErrorMessage(code) { switch (code) { case 1000: return "Normal closure, meaning that the purpose for which the connection was established has been fulfilled."; case 1001: return "An endpoint is \"going away\", such as a server going down or a browser having navigated away from a page."; case 1002: return "An endpoint is terminating the connection due to a protocol error"; case 1003: return "An endpoint is terminating the connection because it has received a type of data it cannot accept (e.g., an endpoint that understands only text data MAY send this if it receives a binary message)."; case 1004: return "Reserved. The specific meaning might be defined in the future."; case 1005: return "No status code was actually present."; case 1006: return "The connection was closed abnormally, e.g., without sending or receiving a Close control frame"; case 1007: return "An endpoint is terminating the connection because it has received data within a message that was not consistent with the type of the message (e.g., non-UTF-8 [http://tools.ietf.org/html/rfc3629] data within a text message)."; case 1008: return "An endpoint is terminating the connection because it has received a message that \"violates its policy\". This reason is given either if there is no other sutible reason, or if there is a need to hide specific details about the policy."; case 1009: return "An endpoint is terminating the connection because it has received a message that is too big for it to process."; case 1010: // Note that this status code is not used by the server, because it can fail the WebSocket handshake instead. return "An endpoint (client) is terminating the connection because it has expected the server to negotiate one or more extension, but the server didn't return them in the response message of the WebSocket handshake. <br /> Specifically, the extensions that are needed are: " + event.reason; case 1011: return "A server is terminating the connection because it encountered an unexpected condition that prevented it from fulfilling the request."; case 1015: return "The connection was closed due to a failure to perform a TLS handshake (e.g., the server certificate can't be verified)."; default: return "Unknown reason"; } } window.addEventListener("load", init, false); |
index.html:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<!DOCTYPE html> <html lang="ja"> <head> <link rel="profile" href="http://gmpg.org/xfn/11" /> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>WebSocket Test with Golang and Javascript</title> </head> <body> <h2>WebSocket Test with Golang and Javascript</h2> <div id="login"><input id="user" /><button onclick="login()">Join</button></div> <div id="send" style="display: none;"><input id="msg" /><button onclick="send()">Send</button></div> <div id="output"></div> <script type="text/javascript" src="./websocket.js"></script> </body> </html> |
See
- https://qiita.com/m0a/items/f6405bc29073a7609050
-
https://stackoverflow.com/questions/30686655/go-program-throwing-error-cannot-find-package-code-google-com-p-go-net-websocke
-
https://qiita.com/nekozuki_twt/items/82974d54db71ee12a5e7
-
https://ashitani.jp/golangtips/tips_time.html